package com.shushan.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.discount.MyDiscountActivity;
import com.shushan.home.bean.MineIndexBean;
import com.shushan.invitecode.InviteCalendarActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.MyCollectionActivity;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.MyWrongTopicActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.pages.ScoreReceiveActivity;
import com.shushan.pages.UserServiceCenterActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.DialRTAService;
import com.shushan.setting.SettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DialogUtil;
import com.shushan.util.OnFingerSuccessListener;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.web.AdvertWebActivity;

/**
 * @ClassName: MineHomeFragment
 * @Desciption: //TODO
 * @author: yichaohua
 * @date: 2018-12-10
 */
public class MineHomeFragment extends BaseHomeFragment implements View.OnClickListener, VerificationCodeView.OnCodeFinishListener, OnFingerSuccessListener {

    private static final String TAG = "MineHomeFragment";

    private ImageView settingImg;
    private ImageView rewardImg;
    private TextView tvChildName;
    private RelativeLayout scoreGuide;
    private RelativeLayout customLayout;
    private ImageView openVipImg;
    private ImageView openSupperVipImg;
    private ImageView openExtractVipImg;
    private ImageView openSectVipImg;
    private ImageView openSupperFlagImg;
    private ImageView openExtractFlagImg;
    private ImageView openSectFlagImg;
    private TextView startText;
    private VerificationCodeView veriCodeView;
    private TextView collectText;
    private TextView mistakeText;
    private TextView couponText;
    private LinearLayout collectLayout;
    private LinearLayout mistakeLayout;
    private LinearLayout couponLayout;

    private MineIndexBean indexBean;
    private BabyApplication babyApplication = BabyApplication.getInstance();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mine_home_fragment,null);

        initView(view);

        getData();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        ChildBean childBean = babyApplication.getCurrentChildBean();
        if(childBean != null && !TextUtils.isEmpty(childBean.childName)){
            tvChildName.setText(childBean.childName);
        }
    }

    private void initView(View view) {
        collectText = view.findViewById(R.id.mine_home_collect_tv);
        mistakeText = view.findViewById(R.id.mine_home_mistake_tv);
        couponText = view.findViewById(R.id.mine_home_coupon_tv);
        collectLayout = view.findViewById(R.id.mine_home_collect_layout);
        collectLayout.setOnClickListener(this);
        mistakeLayout = view.findViewById(R.id.mine_home_mistake_layout);
        mistakeLayout.setOnClickListener(this);
        couponLayout = view.findViewById(R.id.mine_home_coupon_layout);
        couponLayout.setOnClickListener(this);
        openSupperFlagImg = view.findViewById(R.id.mine_vip_supper_img);
        openExtractFlagImg = view.findViewById(R.id.mine_vip_extract_img);
        openSectFlagImg = view.findViewById(R.id.mine_vip_sect_img);
        startText = view.findViewById(R.id.mine_home_start_tv);
        tvChildName = view.findViewById(R.id.tv_child_name);
        ChildBean childBean = babyApplication.getCurrentChildBean();
        if(childBean != null && !TextUtils.isEmpty(childBean.childName)){
            tvChildName.setText(childBean.childName);
        }
        settingImg = view.findViewById(R.id.mine_home_setting_img);
        settingImg.setOnClickListener(this);
        rewardImg = view.findViewById(R.id.mine_home_reward_img);
        rewardImg.setOnClickListener(this);
        scoreGuide = view.findViewById(R.id.mine_home_score_guide_layout);
        scoreGuide.setOnClickListener(this);
        customLayout = view.findViewById(R.id.mine_home_custom_layout);
        customLayout.setOnClickListener(this);
        openVipImg = view.findViewById(R.id.mine_home_open_vip_img);
        openVipImg.setOnClickListener(this);
        openSupperVipImg = view.findViewById(R.id.mine_home_open_super_img);
        openSupperVipImg.setOnClickListener(this);
        openExtractVipImg = view.findViewById(R.id.mine_home_open_extract_img);
        openExtractVipImg.setOnClickListener(this);
        openSectVipImg = view.findViewById(R.id.mine_home_open_sect_img);
        openSectVipImg.setOnClickListener(this);
    }

    private void getData() {
        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.MY_CENTER);
        UrlParse paramParse = new UrlCommParse(getActivity())
                .putValue("child_id",childId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MineIndexBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MineIndexBean mineIndexBean) {
                        if(mineIndexBean != null){
                            indexBean = mineIndexBean;

                            startText.setText(mineIndexBean.stars + "颗");
                            collectText.setText(mineIndexBean.collect_count + "题");
                            mistakeText.setText(mineIndexBean.error_count + "题");
                            couponText.setText(mineIndexBean.card + "张");

                            if(mineIndexBean.vip == 1){
                                openSupperFlagImg.setVisibility(View.VISIBLE);
                            }else {
                                openSupperFlagImg.setVisibility(View.GONE);
                            }

                            if(mineIndexBean.extract == 1){
                                openExtractFlagImg.setVisibility(View.VISIBLE);
                            }else {
                                openExtractFlagImg.setVisibility(View.GONE);
                            }

                            if(mineIndexBean.tb_vip + mineIndexBean.sz_vip
                                    + mineIndexBean.ks_vip + mineIndexBean.ky_vip
                                    + mineIndexBean.dc_vip + mineIndexBean.tl_vip > 0){
                                openSectFlagImg.setVisibility(View.VISIBLE);
                            }else {
                                openSectFlagImg.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onFragmentChecked() {
        getData();
    }

    @Override
    public void onFragmentHided() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mine_home_setting_img:
                String mobile = SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY);
                if (TextUtils.isEmpty(mobile)){
                    startActivity(SettingActivity.class);
                }else {
                    veriCodeView = DialogUtil.showInputParentPswDialog(getActivity(), this, this,this);
                }
                break;
            case R.id.mine_home_reward_img:
                startActivity(MyStarActivity.class);
                break;
            case R.id.mine_home_score_guide_layout:
                startActivity(InviteCalendarActivity.class);
                break;
            case R.id.mine_home_custom_layout:
                startActivity(UserServiceCenterActivity.class);
                break;
            case R.id.mine_home_open_vip_img:
                startActivity(OpenVipSpendActivity.class);
                break;
            case R.id.mine_home_open_super_img:
                startActivity(OpenVipSpendActivity.class);
                break;
            case R.id.mine_home_open_extract_img:
                if(indexBean != null){
                    Intent intent = new Intent(getActivity(), AdvertWebActivity.class);
                    intent.putExtra("title",indexBean.name);
                    intent.putExtra("url",indexBean.url);
                    startActivityAllow(intent);
                }else {
                    showToast("获取的信息为空");
                }
                break;
            case R.id.mine_home_open_sect_img:
                startActivity(OpenSectVipActivity.class);
                break;
            case R.id.btn_find_back_psw:
                DialogUtil.showForgetPswDialog(getActivity(),this);
                break;
            case R.id.btn_cancel:
                DialogUtil.dismissParentSetDialog();
                break;
            case R.id.iv_close_no_bg://忘记密码dialog：×
                DialogUtil.dismissDialog();
                break;
            case R.id.iv_client_phone_num://忘记密码dialog：客服电话
                DialCustom();
                break;
            case R.id.mine_home_collect_layout:
                startActivity(MyCollectionActivity.class);
                break;
            case R.id.mine_home_mistake_layout:
                startActivity(MyWrongTopicActivity.class);
                break;
            case R.id.mine_home_coupon_layout:
                startActivity(MyDiscountActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            startActivity(SettingActivity.class);
            DialogUtil.dismissParentSetDialog();
        }else{
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    @Override
    public void onFingerSuccess() {
        startActivity(SettingActivity.class);
        DialogUtil.dismissParentSetDialog();
    }

    private void DialCustom() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(isChildControl && !SystemUtils.checkUsagePermission(getActivity())){
            showNoUsageDialog();
            return;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
            startActivityAllow(intent);
            DialogUtil.dismissDialog();
            DialogUtil.dismissParentSetDialog();
        }catch (SecurityException se){
            se.printStackTrace();
            showToast("没有打电话权限");
            return;
        }

        if(isChildControl){
            setAllowBack(true);
            ActivityStackManager.getActivityStackManager().popAllActivity();
            Intent intent = new Intent(getActivity(),DialRTAService.class);
            intent.putExtra("allowPackName",Constants.ALLOW_DIAL_PACK_NAME);
            getActivity().startService(intent);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法返回首页，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }
}
